package cc.tuhaolicai.mt.user.mobile.config;

import cc.tuhaolicai.mt.user.mobile.annotation.Mapping;
import cc.tuhaolicai.mt.user.mobile.controller.BaseController;
import com.jfinal.config.Routes;
import com.jfinal.kit.StrKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pro.tools.system.ToolClassSearch;

import java.util.Set;

/**
 * 扫描Controller上的注解，绑定Controller和controllerKey
 */
public class RoutesScan extends Routes {

    private static final Logger log = LoggerFactory.getLogger(RoutesScan.class);

    @SuppressWarnings({"unchecked"})
    @Override
    public void config() {
        setBaseViewPath("/WEB-INF/view"); // 设置路由公共路径

        // 查询所有继承BaseController的子类
        Set<Class<?>> controllerClasses = ToolClassSearch.getClazz(BaseController.class);
        controllerClasses.remove(BaseController.class);

        // 循环处理自动注册映射
        for (Class controller : controllerClasses) {
            // 获取注解对象
            Mapping mappingBind = (Mapping) controller.getAnnotation(Mapping.class);
            if (mappingBind == null) {
                log.warn(controller.getName() + "继承了BaseController，但是没有注解绑定映射路径，请检查是否已经手动绑定 ！！！");
                throw new RuntimeException(controller.getName() + "继承了BaseController，但是没有注解绑定映射路径，请检查是否已经手动绑定 ！！！");
            }

            // 获取映射路径数组
            String[] controllerKeys = mappingBind.value();
            String viewPath = mappingBind.viewPath();
            for (String controllerKey : controllerKeys) {
                String controllerKeyTrim = controllerKey.trim();
                if (StrKit.isBlank(controllerKeyTrim)) {
                    log.error(controller.getName() + "注解错误，映射路径为空");
                    throw new RuntimeException(controller.getName() + "注解错误，映射路径为空");
                }
                // 注册映射
                if (StrKit.notBlank(viewPath)) {
                    add(controllerKeyTrim, controller, viewPath);
                } else {
                    add(controllerKeyTrim, controller);
                }
                log.debug("Controller注册： controller = " + controller + ", " + controllerKeyTrim);
            }
        }
    }

}
